#include "registerwindow.h"
#include "ui_registerwindow.h"
#include <QMessageBox>
#include <QCryptographicHash>


RegisterWindow::RegisterWindow(TcpClient* client,QWidget *parent)
    : QDialog(parent),ui(new Ui::RegisterWindow),m_tcpClient(client)
{
    ui->setupUi(this);
    this->setWindowTitle("注册窗口");

    // 与登录窗口一样，创建网络客户端实例并连接
    // m_tcpClient = new TcpClient(this);
    m_tcpClient->connectToServer("127.0.0.1", 8888);

    // 连接 TcpClient 的信号到我们自己的槽
    connect(m_tcpClient, &TcpClient::serverResponse, this, &RegisterWindow::onServerResponse);
    //连接返回登陆界面的按钮
    connect(ui->backpushButton, &QPushButton::clicked, this, &RegisterWindow::reject);

}

RegisterWindow::~RegisterWindow()
{
    delete ui;
}

void RegisterWindow::on_RegisterpushButton_clicked()
{
    QString username = ui->usernamelineEdit->text();
    QString password = ui->passwordlineEdit->text();
    QString confirmPassword = ui->confirmpasswordlineEdit->text();

    // --- 前端校验 ---
    if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
        QMessageBox::warning(this, "注册失败", "用户名和密码不能为空！");
        return;
    }
    if (password != confirmPassword) {
        QMessageBox::warning(this, "注册失败", "两次输入的密码不一致！");
        return;
    }

    // --- 构建注册请求 JSON ---
    QJsonObject registerRequest;
    registerRequest["type"] = "register_request";
    registerRequest["username"] = username;

    QByteArray passwordHash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Md5);
    registerRequest["password"] = QString(passwordHash.toHex());

    // --- 发送请求 ---
    m_tcpClient->sendJson(registerRequest);
}


// 处理从服务器收到的所有响应
void RegisterWindow::onServerResponse(const QJsonObject &response)
{
    QString type = response["type"].toString();

    if (type == "register_response") {
        bool success = response["success"].toBool();
        if (success) {
            // 注册成功
            QMessageBox::information(this, "成功", "注册成功！您现在可以使用该账号登录了。");
            this->close(); // 关闭注册窗口
        } else {
            // 注册失败
            QString error = response["error_message"].toString();
            QMessageBox::critical(this, "注册失败", error);
        }
    }
}
